package com.peng.controller;


import com.peng.entity.Permission;
import com.peng.service.PermissionService;
import com.peng.utils.Result;
import com.peng.vo.query.PermissionQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.List;

@RestController
@RequestMapping("/api/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    /**
     * 查询菜单列表
     *
     * @param permissionQueryVo
     * @return
     */
    @GetMapping("/list")
    public Result list(PermissionQueryVo permissionQueryVo) {
        // 调用查询菜单列表方法
        List<Permission> permissionList = permissionService.findPermissionList(permissionQueryVo);
        return Result.ok(permissionList);
    }

    /**
     * 查询上级菜单列表
     *
     * @return
     */
    @GetMapping("/parent/list")
    public Result getParentList() {
        // 调用查询上级菜单列表方法
        List<Permission> permissionList = permissionService.findParentPermissionList();
        return Result.ok(permissionList);
    }

    /**
     * 添加菜单
     *
     * @param permission
     * @return
     */
    @PreAuthorize("hasAuthority('sys:menu:add')")
    @PostMapping("/add")
    public Result add(@RequestBody Permission permission) {
        return permissionService.save(permission) ? Result.ok().message("添加成功") : Result.error().message("添加失败");
    }

    /**
     * 修改菜单
     *
     * @param permission
     * @return
     */
    @PreAuthorize("hasAuthority('sys:menu:edit')")
    @PutMapping("/update")
    public Result update(@RequestBody Permission permission) {
        return permissionService.updateById(permission) ? Result.ok().message("修改成功") : Result.error().message("修改失败");
    }

    /**
     * 删除菜单
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        return permissionService.removeById(id) ? Result.ok().message("删除成功") : Result.error().message("删除失败");
    }

    /**
     * 检测菜单是否有子菜单
     * @param id
     * @return
     */
    @GetMapping("/check/{id}")
    public Result check(@PathVariable Long id){
        // 判断菜单是否有子菜单
        if (permissionService.hasChildrenOfPermission(id)){
            return Result.exist().message("该菜单下有子菜单，无法删除");
        }
        return Result.ok();
    }
}

